﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Runtime.InteropServices;

namespace BabyOffice
{
    class ProcessManager
    {       
            [DllImport("kernel32.dll")]
            private static extern IntPtr _lopen(string lpPathName, int iReadWrite);

            [DllImport("kernel32.dll")]
            private static extern bool CloseHandle(IntPtr hObject);

            private static int OF_READWRITE = 2;
            private static int OF_SHARE_DENY_NONE = 0x40;
            private static readonly IntPtr HFILE_ERROR = new IntPtr(-1);

            /// <summary>
            /// 判断文是否被占用
            /// </summary>
            /// 
            /// 
            /// 
            /// <param name="filePath"></param>
            /// <returns></returns>
            public static bool FileIsUsing(string filePath)
            {
                bool result = false;
                IntPtr vHandle = _lopen(filePath, OF_READWRITE | OF_SHARE_DENY_NONE);
                if (vHandle == HFILE_ERROR)
                {
                    result = true;
                }
                CloseHandle(vHandle);
                return result;
            }          
          
            /// <summary>
            /// 杀死EXCEL进程
            /// </summary>
            public static void KillExcelProcess()
            {
                KillProcess("Excel");
            }

            /// <summary>
            /// 杀死EXCEL进程
            /// </summary>
            public static void KillWordProcess()
            {
                KillProcess("Word");
            }

            /// <summary>
            /// 杀死进程
            /// </summary>
            public static void KillProcess(string processName)
            {
                System.Diagnostics.Process[] excelProcess = System.Diagnostics.Process.GetProcessesByName(processName);
                foreach (System.Diagnostics.Process process in excelProcess)
                {
                    if (process != null)
                    {
                        process.Kill();
                    }
                }
            }

            /// <summary>
            /// 杀死进程
            /// </summary>
            public static bool ProcessIsRun(string processName)
            {
                bool isRun=false;
                System.Diagnostics.Process[] excelProcess = System.Diagnostics.Process.GetProcessesByName(processName);
                foreach (System.Diagnostics.Process process in excelProcess)
                {
                    if (process != null)  
                        isRun =true; 
                }
                return isRun;
            }        
       
    }
}
